/**
 * Created by linwei on 7/27/2016.
 */

;$(function() {
    // 管道
    var $pipeline = $('#JQ_pipeline').select3();
    // 管段
    var $segment = $('#pipeSegmentArr').select3({
        title: '管段'
    });
    //主要威胁因素
    var $darg=$('#high').select3();
    DyyBase.ajax(DyyBase.root_path+'/comm/codes.json?majorCode=RA_MAIN_THREATS', {}, function (dataset) {
        var json = DyyBase.getSelect(dataset);
        json.shift();
        $darg.add(json);
    });
    //风险等级
    var $highLeve = $('#highLeve').select3();
    DyyBase.ajax(DyyBase.root_path+'/comm/codes.json?majorCode=RA_RISK_GRADE', {}, function (dataset) {
        var json = DyyBase.getSelect(dataset);
        json.shift();
        $highLeve.add(json);
    });

    // 起点位置
    var $begin = $('#JQ_begin').select3({
        title: '起点位置',
        server: true,
        mileType: 'float',
        param: {'pipeLineId': $pipeline, 'pipeSegmentId': $segment}
    });
    // 终点位置
    var $end = $('#JQ_end').select3({
        title: '终点位置',
        server: true,
        mileType: 'float',
        param: {'pipeLineId': $pipeline, 'pipeSegmentId': $segment, 'beginSignId': $begin}
    });
    //触发管道
    $pipeline.element.on('select', function (e, v) {
        var id = v || $pipeline.val();
        if (id) {
            // 管段
            DyyBase.ajax(DyyBase.url_segment(), {pipeLineId: id}, function (dataset) {
                var json = DyyBase.getSelect(dataset);
                $segment.add(json);
            });
            // 起点 & 终点
            DyyBase.ajax(DyyBase.url_pipe_pos(), {pipeLineId: id}, function (dataset) {
                var begin = DyyBase.getPos(dataset, 'begin', true);
                var end = DyyBase.getPos(dataset, 'end',true);
                $begin.add(begin);
                $end.add(end);
            });

        } else {
            $segment.add([]);
            $begin.add([]);
            $end.add([]);
        }
    });
    // 触发管段
    $segment.element.on('select', function (e, v) {
        var id = v || $segment.val();
        if (id) {
            // 起点 & 终点
            DyyBase.ajax(DyyBase.url_segment_pos(), {pipeSegmentId: id}, function (dataset) {
                var begin = DyyBase.getPos(dataset, 'begin',true);
                var end = DyyBase.getPos(dataset, 'end',true);
                $begin.add(begin);
                $end.add(end);
            });
        } else {
            $begin.add([]);
            $end.add([]);
        }
    });
// 初始化日期控件
    var $date_01 = $('#JQ_input_date_01');
    var $date_02 = $('#JQ_input_date_02');

    // 搜索条件
    var filter = {
        // 获得表单项
        getCondition: function(data){
            var filter = {};
            if (data) {
                if (data.start == 0) {
                    filter['jsonBean.pageNum'] = 1;
                } else {
                    filter['jsonBean.pageNum'] = data.start / 10 + 1;
                }
                filter['jsonBean.pageCount'] = data.length;
            }

            //if(!DyyBase.search){
            //    return filter;
            //}
            // 管道id
            filter.pipeLineId = function(){
                 var v=$pipeline.val();
                 if (v){
                     return v;
                 }
                return '';
            }();
            // 风险等级
            filter.riskGrade = function(){
                var v=$highLeve.val();
                if(v){
                    return v;
                }
                return '';
            }();
            // 主要威胁因素
            filter.mainThreats = function(){
                var v=$darg.val();
                if(v){
                    return v;
                }
                return '';
            }();
            //起点绝对距离
            filter.fromMileage=function(){
                var v= $begin.val('mile');
                if (DyyBase.notEmpty(v)){
                    return v;
                }
                return '';
            };
            //终点绝对距离
            filter.toMileage=function(){
                var v= $end.val('mile');
                if (DyyBase.notEmpty(v)){
                    return v;
                }
                return '';
            };
            // 采取的风险控制措
            filter.controlMeasures = function(){
                return $("#controlMeasuresSearch").hasClass('active') ? "1" : "0";
            }();
            return filter;
        },
        //获得导出返回参数
        getExport:function(){
            var dataExportV = {};
            dataExportV.pipeLineId = function(){
                var v=$pipeline.val();
                if(v){
                    return v;
                }
                return '';
            }();
            dataExportV.pipeLineName = function(){
                var v=$pipeline.val('text');
                if(v){
                    return v;
                }
                return '';
            }();
            dataExportV.riskGrade=function(){
                var v=$highLeve.val();
                if(v){
                    return v;
                }
                return '';
            }();
            dataExportV.mainThreats=function(){
                var v=$darg.val();
                if(v){
                    return v;
                }
                return '';
            }();
            dataExportV.controlMeasures=function(){
                var v=$("#controlMeasuresSearch").hasClass('active') ? "1" : "0";
                if(v){
                    return v;
                }
                return '';
            }();
            dataExportV.fromMileage=function(){
                var v=$begin.val('mile');
                if(v){
                    return v;
                }
                return '';
            }();
            dataExportV.toMileage=function(){
                var v=$end.val('mile');
                if(v){
                    return v;
                }
                return '';
            }();
            return dataExportV;
        },
        // 执行查询后的筛选对象
        getExportFilter: function(){
            return filter.getCondition();
        }
    };

    // 导出
    $('#btn_export').on('click', function() {
        var param = filter.getExport;
        if(param instanceof Function){
            param = param();
        }
        $(this).EXPT({
            type: 'name',
            name: param.pipeLineName+'风险评价数据',
            param: param,
            server: DyyBase.root_path +　'/riskMgr/riskAssessment/export.json'

        });
    });
    // 添加gis
    $('#JQ_gis_btn').on('click', function() {
        localRiskGis();
    });
    //统计
    $('#JQ_total_btn').on('click',function(){
        window.location.href=DyyBase.root_path+'/riskMgr/riskAssessment/toStatistics.html';
    });
    //查询
    $('#JQ_search').on('click', function() {
        if(DT01){
            DT01.draw();
            filter.getExportFilter=filter.getCondition();
        }
        //DyyBase.search = true;
        //DT01.draw();
        //statisticsPercent();
    });

     // 初始化表格数据
    var $table_01 = $('#JQ_datatable_01').checkbox3();
    var DT01 = $table_01.DataTable({
        'language': {
            'paginate': {
                'next': '下一页',
                'previous': '上一页'
            },
            'info': '本次检索共 _TOTAL_ 条，每页显示 10 条，共 _PAGES_ 页 ',
            'lengthMenu': '每页显示 _MENU_ 条',
            'search': '搜索',
            'searchPlaceholder': '输入名称',
            'zeroRecords': function(){
                // 无数据
                return '<div class="zy-datatable-empty"><p><img src="'+RiskComm.local_path()+'/static/img/no_data.png"></p><h2>管道管理的太好了！</h2><p class="c-90">未发现其他管体风险</p></div>';
            },
            'infoEmpty': '',
            'infoFiltered': ' - 从 _MAX_ 条数据中搜索',
            'loadingRecords': '等待载入数据...'
        },
        'autoWidth': false,
        'serverSide': true,
        'pageLength': 10,
        'ordering': false,
        'processing': false,
        'searching': false,
        'lengthChange': false,
        'ajax': function(data, callback){
            // 查询数据
            var param = filter.getCondition(data);
            DyyBase.ajax(RiskComm.local_path()+"/riskMgr/riskAssessment/queryRiskAssessment.json",param,function(dataset){

                // 封装返回数据
                var returnData = {};
                returnData.draw = data.draw;
                returnData.recordsTotal = dataset.result.total;
                returnData.recordsFiltered = dataset.result.total;
                returnData.data = DyyBase.clearNull(dataset.result.list);

                // 回调渲染
                callback(returnData);
            });
        },
        'drawCallback': function(settings){
            // 渲染
        },
        'columns': [
            {'data': 'pipeLineName',render:function(data, type, row){
                return '<span title="'+data+'">'+data+'</span><input name="data_gis_id" type="hidden" value="'+row.gisId+'">';
            }},
            {'data': 'name',render:function(data){
                return '<span title="'+data+'">'+data+'</span>';
            }},
            {'data': 'riskGrade',render:function(data){
                return '<span title="'+data+'">'+data+'</span>';
            }},
            {'data': 'mainThreats',render:function(data){
                return '<span title="'+data+'">'+data+'</span>';
            }},
            {'data': 'riskProposal',render:function(data){
                return '<span title="'+data+'">'+data+'</span>';
            }},
            {'data': 'fromLocationDescription',render:function(data){
                return '<span title="'+data+'">'+data+'</span>';
            }},
            {'data': 'toLocationDescription',render:function(data){
                return '<span title="'+data+'">'+data+'</span>';
            }},
            {'data': 'controlMeasures',render:function(data){
                return '<span title="'+data+'">'+data+'</span>';
            }},
            {'data': 'isControllable',render:function(data){
                var color = '';
                if(data=="否"){
                    color='lsk-no-color';
                }
                return '<span title="'+data+'" class="' + color + '">'+data+'</span>';
            }},
            {'data': 'id',render:function(data){
                return '<i data-defectId="'+data+'" class="zy-details-icon" title="详情"></i>';
            }}
        ]
    });


    // 展开详情
    $table_01.delegate('i.zy-details-icon','click',function(){
        // 当前按钮
        var $this_i = $(this);
        // 携带的ID
        var defectId = $this_i.attr('data-defectId');
        // 当前父级 tr
        var $tr = $this_i.parent('td').parent('tr');
        // 当前父级 tbody
        var $tbody = $this_i.parent('td').parent('tr').parent('tbody');
        // 已经存在的动态 tr ?
        var $dy_tr = $tbody.find('tr[data-defectId="'+defectId+'"]');

        // 激活当前按钮选中样式
        $table_01.find('i.zy-details-icon').removeClass('active');
        $this_i.addClass('active');

        // 隐藏其他动态行
        $table_01.find('tr.zy-dy-tr').hide();

        // 有则显示 无则填充
        if($dy_tr.length > 0){
            $dy_tr.show();
        }else{
            fillAdviseDetails($tr,defectId);
        }
    });

    // 收起详情
    $table_01.delegate('button.zy-pack-up','click',function(){
        var $this_btn = $(this);
        var defectId = $this_btn.attr('data-defectId');
        $table_01.find('tr[data-defectId="'+defectId+'"]').hide();
        $table_01.find('i.zy-3-icon').removeClass('active');
    });

    // 填充详情
    function fillAdviseDetails(tr,id){
        var data_row = DT01.row(tr).data(); // 行数据
        var $dy_tr = $('<tr class="zy-dy-tr" data-defectId="'+id+'"><td colspan="10"><div class="zy-details-box"></div></td></tr>');
        var $dy_box = $dy_tr.find('div.zy-details-box');
        var html = '<div class="zy-dy-inner"><div class="zy-dy-p">'
            +'<p>统一编号：'+data_row.code+'</p>'
            +'<p>管道名称：'+data_row.pipeLineName+'</p>'
            +'<p>风险段编号：'+data_row.customNumber+'</p>'
            +'<p>风险段名称：'+data_row.name+'</p>'
            +'<p>风险管段长度（m）：'+data_row.length+'</p>'
            +'<p>起始绝对里程：'+data_row.fromMileage+'</p>'
            +'<p>起始最终参考点：'+data_row.fromReference+'</p>'
            +'<p>起始相对最近参考点距离（m）：'+data_row.fromReferenceDistance+'</p>'
            +'<p>终点绝对里程：'+data_row.toMileage+'</p>'
            +'<p>终点最终参考点：'+data_row.toReference+'</p>'
            +'<p>终点相对最近参考点距离（m）：'+data_row.toReferenceDistance+'</p>'
            +'<p>起点位置描述：'+data_row.fromLocationDescription+'</p>'
            +'<p>终点位置描述：'+data_row.toLocationDescription+'</p>'
            +'<p>分段依据：'+data_row.riskaCcroding+'</p>'
            +'<p>地区等级：'+data_row.areaLevel+'</p>'
            +'<p>风险评价方法：'+data_row.evaluateMethod+'</p>'
            +'<p>相对风险评分：'+data_row.relativeRiskScore+'</p>'
            +'<p>第三方破坏评分：'+data_row.damageScore+'</p>'
            +'<p>腐蚀评分：'+data_row.corrosionScore+'</p>'
            +'<p>设计与施工缺陷评分：'+data_row.desConstrScore+'</p>'
            +'<p>地质灾害评分：'+data_row.geohazardScore+'</p>'
            +'<p>误操作评分：'+data_row.operationScore+'</p>'
            +'<p>泄漏影响系数：'+data_row.leadCoefficient+'</p>'
            +'<p>风险等级：'+data_row.riskGrade+'</p>'
            +'<p>主要威胁因素：'+data_row.mainThreats+'</p>'
            +'<p>完整性评价建议：'+data_row.riskProposal+'</p>'
            +'<p>风险减缓建议措施：'+data_row.measure+'</p>'
            +'<p>风险是否已控制到可接受范围之内：'+data_row.isControllable+'</p>'
            +'<p>采取的风险控制措施：'+data_row.controlMeasures+'</p>'
            +'<p>实施时间：'+data_row.implementDate+'</p>'
            +'<p>风险评价时间：'+data_row.evaluateTime+'</p>'
            +'<p>风险评价单位：'+data_row.evaluateCompany+'</p>'
            +'<p>下次风险评价时间：'+data_row.nextEvaluateTime+'</p>'
            +'<p>记录人：'+data_row.recrder+'</p>'
            +'<p>记录时间：'+data_row.recordTime+'</p>'
            +'<p>备注：'+data_row.remark+'</p>'
            +'<div class="clear"></div>'
            +'</div><div class="zy-dy-footer" style="padding:0 0 20px 0"><button data-defectId="'+id+'" class="zy-button  zy-pack-up" type="button"><i></i>收起</button></div></div>';
        // 内部装入 html
        $dy_box.html(html);
        // 后方插入 tr
        tr.after($dy_tr);
    }

    // 导出文件
    //function riskExport() {
    //    //DyyBase.search = true;
    //    //var v = filter.getCondition();
    //    //console.log(v);
    //
    //    var form = createForm(RiskComm.local_path()+ '/riskMgr/riskAssessment/export.json');
    //    form.submit();
    //    form.remove();
    //}

    //function createInput(obj) {
    //    var _name = obj.name;
    //    var _value = obj.value;
    //
    //    var _input = $('<input>');
    //    _input.attr('type', 'hidden');
    //    _input.attr('name', _name);
    //    _input.attr('value', _value);
    //    return _input;
    //}
    //
    //function createForm(actionUrl) {
    //    var form = $("<form>");
    //    form.attr('style', 'display:none');
    //    form.attr('target', '');
    //    form.attr('method', 'post');
    //    form.attr('action', actionUrl);
    //    $('body').append(form);
    //    form.append(createInput({name:"pipeLineId", value:$pipeline.val()}));
    //    form.append(createInput({name:"riskGrade", value:$highLeve.val()}));
    //    form.append(createInput({name:"mainThreats", value:$darg.val()}));
    //    form.append(createInput({name:"fromMileage", value:$begin.val('mile')}));
    //    form.append(createInput({name:"toMileage", value:$end.val('mile')}));
    //    form.append(createInput({name:"controlMeasures", value:$("#controlMeasuresSearch").hasClass('active') ? "1" : "0"}));
    //
    //    return form;
    //}

    /* 页面跳转 */
    function localRiskGis(){





        $("#JQ_gis_btn").show();


        var arr = [];
        var $data = $('input[name="data_gis_id"]');
        var $form = $('#JQ_gis_form');
        $data.each(function(){
            var $this = $(this);
            arr.push($this.val());
        });
        var $input = $('<input type="hidden">');
        $input.prop('name','gisArray').val(arr.join(','));
        $form.append($input);
        $form.submit();
        /*$.each(data, function(i) {
         //_gis_array.push(data[i].value);
         var $input = $('<input type="hidden">');
         $input.prop('name',).val();
         });*/

        //var _gis_array = new Array();
        //var data = document.getElementsByName("data_gis_id");
        //$.each(data, function(i, evalue) {
        //    _gis_array.push(data[i].value);
        //});

    }

})



$('.xyf-toggle-form-div').on('click',function(){
    if($(this).hasClass('active')){
        $(this).removeClass('active')
        $('.lsk-pick-line').removeClass('none');
    }else {
        $(this).addClass('active');
        $('.lsk-pick-line').addClass('none');
    }
})

